package com.example.fisttestproject.database;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import com.example.fisttestproject.dao.UserDao;
import com.example.fisttestproject.entity.User;
import com.example.fisttestproject.util.Const;

import java.io.File;

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();

    private static volatile AppDatabase INSTANCE;
    /**
     * 单例模式
     */
    public  static AppDatabase getDatabase(final Context context) {
        File dbDir = new File(context.getFilesDir(), "db");
        if (!dbDir.exists()) {
            dbDir.mkdir(); // 创建目录
        }


        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, Const.GLOBAL.DB_NAME)
                            .fallbackToDestructiveMigration()
                            .allowMainThreadQueries()
//                            .createFromFile(new File(dbDir,Const.GLOBAL.DB_NAME+".db"))
                            .build();
                }
            }
        }
        return INSTANCE;
    }


}